<template>
  <a-spin :loading="spinLoading" :size="35" class="w-[100%]" tip="正在处理, 请稍候...">
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <!-- 基本信息区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">基本信息</h2>
        <a-form
            ref="formRef"
            :model="form"
            :rules="rules"
            auto-label-width
            layout="vertical"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="enterpriseName" label="企业名称" required>
                <a-input v-model="form.enterpriseName" placeholder="请输入企业名称"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="enterprisePerson" label="企业联系人" required>
                <a-input v-model="form.enterprisePerson" placeholder="请输入企业联系人"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="enterpriseMobile" label="企业联系方式" required>
                <a-input
                    v-model="form.enterpriseMobile"
                    placeholder="请输入企业联系方式"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 修改时，只询问是否重置密码，选择重置密码后，才能手动输入密码 -->
          <a-form-item
              v--if="props.params.operationType === proxy.operationType.update.type"
              class="w-[49%]"
              field="enterprisePassword"
              row-class="form-label"
          >
            <template #label>
              <template class="flex items-center justify-between">
                <span>
                  用户密码
                  <a-tooltip
                      content="勾选重置密码后可输入密码进行重置，不勾选表示不修改密码"
                  >
                    <icon-question-circle style="color: var(--color-text-4)"/>
                  </a-tooltip>
                </span>
                <a-checkbox
                    v-model="isResetPassword"
                    :value="true"
                    @change="isResetPasswordChange"
                >重置密码
                </a-checkbox
                >
              </template>
            </template>
            <!-- 密码框 -->
            <a-input-password
                v-model="form.enterprisePassword"
                :disabled="!isResetPassword"
                placeholder="用户密码"
            />
          </a-form-item>
        </a-form>
      </div>

      <!-- 证件信息区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">证件信息</h2>

        <!-- 图片展示区域 -->
        <a-row :gutter="16">
          <!-- 营业执照 -->
          <a-col :span="8" class="mb-4">
            <a-card title="营业执照">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseBusinessLicense
                    "
                      type="text"
                      @click="enterpriseBusinessLicenseVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseBusinessLicense
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseBusinessLicense)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseBusinessLicenseUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="
                    form.enterpriseBusinessLicense && form.enterpriseBusinessLicenseUrl
                  "
                    :preview-visible="enterpriseBusinessLicenseVisiable"
                    :src="form.enterpriseBusinessLicenseUrl"
                    width="100%"
                    @preview-visible-change="enterpriseBusinessLicenseVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 税务登记证 -->
          <a-col :span="8" class="mb-4">
            <a-card title="税务登记证">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseTax
                    "
                      type="text"
                      @click="enterpriseTaxVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseTax
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseTax)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseTaxUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.enterpriseTax && form.enterpriseTaxUrl"
                    :preview-visible="enterpriseTaxVisiable"
                    :src="form.enterpriseTaxUrl"
                    width="100%"
                    @preview-visible-change="enterpriseTaxVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 组织机构代码证 -->
          <a-col :span="8" class="mb-4">
            <a-card title="组织机构代码证">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseCode
                    "
                      type="text"
                      @click="enterpriseCodeVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseCode
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseCode)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseCodeUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.enterpriseCode && form.enterpriseCodeUrl"
                    :preview-visible="enterpriseCodeVisiable"
                    :src="form.enterpriseCodeUrl"
                    width="100%"
                    @preview-visible-change="enterpriseCodeVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 法人身份证正面 -->
          <a-col :span="8" class="mb-4">
            <a-card title="法人身份证正面">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseIdcard1
                    "
                      type="text"
                      @click="enterpriseIdcard1Visiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseIdcard1
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseIdcard1)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseIdcard1UploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.enterpriseIdcard1 && form.enterpriseIdcard1Url"
                    :preview-visible="enterpriseIdcard1Visiable"
                    :src="form.enterpriseIdcard1Url"
                    width="100%"
                    @preview-visible-change="enterpriseIdcard1Visiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 法人身份证反面 -->
          <a-col :span="8" class="mb-4">
            <a-card title="法人身份证反面">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseIdcard2
                    "
                      type="text"
                      @click="enterpriseIdcard2Visiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseIdcard2
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseIdcard2)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseIdcard2UploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.enterpriseIdcard2 && form.enterpriseIdcard2Url"
                    :preview-visible="enterpriseIdcard2Visiable"
                    :src="form.enterpriseIdcard2Url"
                    width="100%"
                    @preview-visible-change="enterpriseIdcard2Visiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>

          <!-- 授权委托书 -->
          <a-col :span="8" class="mb-4">
            <a-card title="授权委托书">
              <template #extra>
                <div class="flex items-center">
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseAttorney
                    "
                      type="text"
                      @click="enterpriseAttorneyVisiable = true"
                  >
                    <icon-eye/>
                  </a-button>
                  <a-button
                      v-if="
                      props.params.operationType === proxy.operationType.update.type &&
                      form.enterpriseAttorney
                    "
                      type="text"
                      @click="onDownLoad(form.enterpriseAttorney)"
                  >
                    <icon-download/>
                  </a-button>
                </div>
              </template>
              <div class="image-container">
                <uploadFile
                    v-if="props.params.operationType === proxy.operationType.add.type"
                    ref="enterpriseAttorneyUploadfFileRef"
                    :file-source="fs"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg,.pdf"
                    list-type="picture"
                    source-type="proxy"
                />
                <a-image
                    v-else-if="form.enterpriseAttorney && form.enterpriseAttorneyUrl"
                    :preview-visible="enterpriseAttorneyVisiable"
                    :src="form.enterpriseAttorneyUrl"
                    width="100%"
                    @preview-visible-change="enterpriseAttorneyVisiable = $event"
                />
                <div v-else class="empty-image-placeholder">
                  <icon-file-image class="text-gray-300 text-2xl"/>
                  <span class="text-gray-400 text-xs mt-2">暂无图片</span>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 操作按钮区域 -->
      <div class="flex justify-end mt-8">
        <a-space>
          <a-button class="px-6" @click="cancelBtnClick()">取消</a-button>
          <a-button class="px-6" type="primary" @click="okBtnClick()">确定</a-button>
        </a-space>
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch} from "vue";
import {
  addEnterpriseAccountApi,
  getEnterpriseAccountByEnterpriseAccountIdApi,
  updateEnterpriseAccountByEnterpriseAccountIdApi
} from "~/api/lindi/enterpriseAccount.js";
import {fileSource} from "~/utils/sys.js";
import uploadFile from "~/components/uploadFile/index.vue";
import {downloadFileApi} from "~/api/basic/file.js";
//全局实例
const {proxy} = getCurrentInstance();
//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.commonNumberStatus]);
//接收父组件参数
const props = defineProps({
  params: {
    type: Object,
    default: () => {
    },
  },
});
//父组件函数
const emits = defineEmits(["ok", "cancel"]);
//加载中...
const spinLoading = ref(false);
//表单ref
const formRef = ref(null);
//是否重置密码
const isResetPassword = ref(false);
//是否重置密码 change事件
const isResetPasswordChange = (val) => {
  isResetPassword.value = val;
};
const fs = fileSource.lindi_enterprise_registration_img.key;
//默认图片
const defaultImageUrl =
    "https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp";
//图片预览状态
const enterpriseBusinessLicenseVisiable = ref(false);
const enterpriseTaxVisiable = ref(false);
const enterpriseCodeVisiable = ref(false);
const enterpriseIdcard1Visiable = ref(false);
const enterpriseIdcard2Visiable = ref(false);
const enterpriseAttorneyVisiable = ref(false);
//文件上传组件
const enterpriseBusinessLicenseUploadfFileRef = ref(null);
const enterpriseTaxUploadfFileRef = ref(null);
const enterpriseCodeUploadfFileRef = ref(null);
const enterpriseIdcard1UploadfFileRef = ref(null);
const enterpriseIdcard2UploadfFileRef = ref(null);
const enterpriseAttorneyUploadfFileRef = ref(null);
//表单
const form = reactive({
  //企业注册ID
  enterpriseAccountId: null,
  //企业名称
  enterpriseName: null,
  //企业联系人
  enterprisePerson: null,
  //企业联系方式
  enterpriseMobile: null,
  //企业用户密码
  enterprisePassword: null,
  //营业执照
  enterpriseBusinessLicense: null,
  enterpriseBusinessLicenseUrl: null,
  //税务登记证
  enterpriseTax: null,
  enterpriseTaxUrl: null,
  //licenses
  enterpriseCode: null,
  enterpriseCodeUrl: null,
  //企业法人身份证正面
  enterpriseIdcard1: null,
  enterpriseIdcard1Url: null,
  //企业法人身份证反面
  enterpriseIdcard2: null,
  enterpriseIdcard2Url: null,
  //授权委托书
  enterpriseAttorney: null,
  enterpriseAttorneyUrl: null,
  //状态 0审核中 1审核通过 2审核未通过
  status: null,
});
//表单校验规则
const rules = {
  enterpriseName: [{required: true, message: "企业名称不能为空", trigger: "submit"}],
  enterprisePerson: [
    {required: true, message: "企业联系人不能为空", trigger: "submit"},
  ],
  enterpriseMobile: [
    {required: true, message: "企业联系方式不能为空", trigger: "submit"},
  ],
};
//下载文件
const onDownLoad = (fileId) => {
  if (!fileId) {
    proxy.$msg.warning("文件不存在");
    return;
  }

  spinLoading.value = true;
  downloadFileApi(fileId)
      .then((response) => {
        // 创建Blob对象
        const blob = new Blob([response.data]);
        // 创建下载链接
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        // 获取文件名，如果响应头中有文件名则使用，否则使用默认名称
        const contentDisposition = response.headers["content-disposition"];
        let fileName = "下载文件";
        if (contentDisposition) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(contentDisposition);
          if (matches != null && matches[1]) {
            fileName = decodeURIComponent(matches[1].replace(/['"]/g, ""));
          }
        }
        link.download = fileName;
        // 触发点击下载
        document.body.appendChild(link);
        link.click();
        // 清理
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
        proxy.$msg.success("文件下载成功");
      })
      .catch((error) => {
        console.error("文件下载失败:", error);
        proxy.$msg.error("文件下载失败");
      })
      .finally(() => {
        spinLoading.value = false;
      });
};
//确定 -> 点击
const okBtnClick = () => {
  //表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    // 添加模式下获取所有上传文件的ID
    if (props.params.operationType === proxy.operationType.add.type) {
      // 获取各个文件上传组件的文件ID
      form.enterpriseBusinessLicense =
          enterpriseBusinessLicenseUploadfFileRef.value?.getUploadFileId() || null;
      form.enterpriseTax = enterpriseTaxUploadfFileRef.value?.getUploadFileId() || null;
      form.enterpriseCode = enterpriseCodeUploadfFileRef.value?.getUploadFileId() || null;
      form.enterpriseIdcard1 =
          enterpriseIdcard1UploadfFileRef.value?.getUploadFileId() || null;
      form.enterpriseIdcard2 =
          enterpriseIdcard2UploadfFileRef.value?.getUploadFileId() || null;
      form.enterpriseAttorney =
          enterpriseAttorneyUploadfFileRef.value?.getUploadFileId() || null;
    }

    //添加
    if (props.params.operationType === proxy.operationType.add.type) {
      spinLoading.value = true;
      addEnterpriseAccountApi(form)
          .then(() => {
            proxy.$msg.success(proxy.operationType.add.success);
            emits("ok");
          })
          .finally(() => {
            spinLoading.value = false;
          });
    }
    //修改
    if (props.params.operationType === proxy.operationType.update.type) {
      spinLoading.value = true;
      updateEnterpriseAccountByEnterpriseAccountIdApi(form)
          .then(() => {
            proxy.$msg.success(proxy.operationType.update.success);
            emits("ok");
          })
          .finally(() => {
            spinLoading.value = false;
          });
    }
  });
};
//取消 -> 点击
const cancelBtnClick = () => {
  emits("cancel");
};
//加载企业注册详细信息
const loadEnterpriseAccountInfo = (enterpriseAccountId) => {
  spinLoading.value = true;
  getEnterpriseAccountByEnterpriseAccountIdApi(enterpriseAccountId)
      .then((res) => {
        //数据赋值
        if (res) {
          for (let key in res) {
            if (form.hasOwnProperty(key)) {
              form[key] = res[key];
            }
          }
        }
      })
      .finally(() => {
        spinLoading.value = false;
      });
};
//监听参数变化
watch(
    () => props.params,
    (newVal, oldVal) => {
      //参数ID
      if (props.params.enterpriseAccountId) {
        //加载参数信息
        loadEnterpriseAccountInfo(props.params.enterpriseAccountId);
      }
    },
    {deep: true, immediate: true}
);
</script>
<style scoped>
/* 原有样式保留 */
.actions {
  @apply flex flex-row justify-center items-center px-1;
}

.action {
  @apply flex items-center justify-center w-6 h-6 rounded-full cursor-pointer transition-all duration-100;
}

.action:hover {
  @apply bg-[var(--color-fill-3)];
}

.actions-outer .action:hover {
  @apply text-white;
}

.empty-image-placeholder {
  @apply w-full h-40 flex flex-col justify-center items-center border border-dashed border-[var(--color-border-2)] rounded bg-[var(--color-fill-1)];
}

/* 统一图片容器高度 */
:deep(.arco-image) {
  @apply h-40 overflow-hidden;
}

:deep(.arco-image-img) {
  @apply object-contain h-4/5;
}

/* 统一上传组件高度 */
:deep(.arco-upload-list-picture .arco-upload-list-item),
:deep(.arco-upload-trigger-picture) {
  @apply h-40;
}

/* 增加表单项间距 */
:deep(.arco-form-item) {
  @apply mb-4;
}

/* 图片容器样式 */
.image-container {
  @apply h-40 flex justify-center items-center;
}

/* 卡片样式调整 */
:deep(.arco-card-body) {
  @apply p-2;
}

:deep(.arco-card-header) {
  @apply pb-2;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  @apply transition-all duration-300;
}

:deep(.arco-btn-text) {
  @apply hover:bg-[var(--color-fill-2)] rounded-full w-8 h-8 flex items-center justify-center p-0 mx-1;
}

/* 表单样式优化 */
:deep(.arco-input) {
  @apply transition-all duration-300;
}

:deep(.arco-form-item-label-text) {
  @apply font-medium;
}

/* 卡片标题样式 */
:deep(.arco-card-header-title) {
  @apply text-[var(--color-text-1)] font-medium;
}
</style>
